package de.rj.urwalking.data.survey;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import de.rj.urwalking.R;
import de.rj.urwalking.config.Constants;

/**
 * 
 * A Question that can be answered with free text. Its UI consists of the question itself and a text field for the
 * answer.
 * 
 * @author rjj
 * 
 */

public class FreeTextQuestion extends Question {

	private static final long serialVersionUID = 1L;
	private String answerCandidate = "";

	public FreeTextQuestion(int id, int itemNumber, String text, int scaleId, int screen) {
		super(id, itemNumber, text, scaleId, screen);

	}

	@Override
	public View buildView(final Context context, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		// build UI from xml and get the two elements
		View questionView = inflater.inflate(R.layout.question_freetext, parent, false);
		TextView questionText = (TextView) questionView.findViewById(R.id.questionText);
		EditText answerEditText = (EditText) questionView.findViewById(R.id.answerEditText);

	
		// set question text and answer (if already existing)
		questionText.setText(getText());
		answerEditText.setText(getAnswer().getTextAnswer());

		answerEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				answerCandidate = s.toString();
				mCallback.onAnswerChanged();
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

		answerEditText.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {

				if (!hasFocus) {
					InputMethodManager imm = (InputMethodManager) context
							.getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

					// only update answer if it is not the same one that is already saved
					if (!getAnswer().getTextAnswer().equals(answerCandidate)) {
						updateAnswer(answerCandidate);
					}
				}

			}
		});

		return questionView;

	}

	public void forceAnswerSave() {
		updateAnswer(answerCandidate);
	}

	@Override
	public boolean hasBeenAnswered() {

		// A FreeTextQuestion is considered as answered if the answer is not the empty String.
		if (answerCandidate.equals(Constants.EMPTY_STRING)) {
			return false;
		} else {
			return true;
		}
	}

}
